package primalgorithms.other;

import java.util.Stack;

public class _05IsValid {
    public static boolean isValid(String s) {
        //括号匹配问题
        if (s.length() < 2){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0;i < s.length();i++){
            char nowChar = s.charAt(i);
            if (nowChar=='(' || nowChar=='[' || nowChar=='{'){
                stack.push(nowChar);
            }else {
                if (stack.isEmpty()){
                    return false;
                }else {
                    if (ifMatch(stack.peek(),nowChar)){
                        stack.pop();
                    }else {
                        return false;
                    }
                }
            }
        }
        return stack.size() == 0;
    }

    private static boolean ifMatch(Character peek, char nowChar) {
        if ((peek == '(' && nowChar == ')') || (peek == '[' && nowChar == ']') || (peek == '{' && nowChar == '}')){
            return true;
        }
        return false;
    }
}
